//
//  AlipayViewController.swift
//  DollBuy
//
//  Created by 郑东喜 on 2016/12/16.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit

import WebKit

class AlipayViewController: UIViewController,WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate {
    
    
    var webView = WKWebView()
    
    var url : String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()

        //支付宝
        userContentController.add(self as WKScriptMessageHandler, name: "alipay")
        
        
        configuration.userContentController = userContentController
        
        let preferences = WKPreferences()
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        
        webView.uiDelegate = self
        webView.navigationDelegate = self
        
        webView = WKWebView.init(frame: view.bounds, configuration: configuration)
        
        
        //本地加载
        let htmlPath = Bundle.main.path(forResource: "Ali", ofType: "html")
        
        do {
            let fileURL = try NSString.init(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
            let baseURL = NSURL.fileURL(withPath: htmlPath! as String)
            webView.loadHTMLString(fileURL as String, baseURL: baseURL)
        } catch  {
            
        }
        
        
        //        if urlArray.count > 1 {
        //            let urlStr = urlArray.lastObject
        //
        //            webView.load(URLRequest.init(url: URL.init(string: urlStr as! String)!))
        //        } else {
        //            DispatchQueue.main.async {
        //                let url = URL.init(string: "http://yungou.ie1e.com/app/cart.aspx")
        //
        //                self.webView.load(URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 2.0))
        //            }
        //        }
        
        view.addSubview(webView)
        
    }
    
    
    /**
     *  JS 调用 swift 时 webview 会调用此方法
     *
     *  @param userContentController  webview中配置的userContentController 信息
     *  @param message                JS执行传递的消息
     */
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //        print(message.body)
        let msg = message.name
        
        
        
        if msg == "alipay" {
            let dic = message.body as! NSDictionary
            
            var signStr = ""
            
            if ((dic["sign"] as? String) != nil) {
                signStr = dic["sign"] as! String
            } else {
                //回调返回值处理
                return
            }
            
            //接收Web支付回调
            PaymenyModel.shared.alipay(orderString: signStr, comfun: { (dic) in
                
                print("\((#file as NSString).lastPathComponent):(\(#line))")
                print(dic)
                
                self.webView.evaluateJavaScript("callJsAlert('\(dic)')", completionHandler: nil)
            })
            
            
            NotificationCenter.default.addObserver(self, selector: #selector(AlipayViewController.info(notification:)), name: NSNotification.Name(rawValue: "123"), object: nil)
            
        }
    }
    
    func jumpToShop() -> Void {
        let tabBarController = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
        tabBarController.selectedIndex = 3
    }

    
    //获取标题
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.navigationItem.title = self.webView.title
    }
    
    
    
    
    
}

// MARK:- 接收支付宝app接收结果
extension AlipayViewController {
    func info(notification : NSNotification) -> Void {
        
        let dic = notification.userInfo as! [AnyHashable : NSObject] as NSDictionary
        
        let result = dic["re"] as! String
        print(result)
        
        self.webView.evaluateJavaScript("callJsAlert('\(result)')", completionHandler: nil)
        
        
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "123"), object: nil)
    }
}

